import 'package:HealthU/ViewModel/LoginViewModel.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class LoginPage extends StatelessWidget{

  final TextEditingController _usernameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Login"),
      ),

      body: Padding(
        padding: EdgeInsets.all(16.0),
        child:Consumer(
          builder: (context,ref,child){

            final viewModel = ref.watch(loginViewModelProvider);
            

            return Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                TextField(
                  controller: _usernameController,
                  decoration: InputDecoration(
                    labelText: 'Username',
                  ),
                ),
                SizedBox(height: 16.0),
                TextField(
                  controller: _passwordController,
                  obscureText: true,
                  decoration: InputDecoration(
                    labelText: 'Password',
                  ),
                ),
                SizedBox(height: 24.0),
                ElevatedButton(
                  onPressed: viewModel.isLoading
                      ? null
                      : () {
                    final username = _usernameController.text;
                    final password = _passwordController.text;
                    viewModel.login(username, password);
                  },
                  child: viewModel.isLoading
                      ? CircularProgressIndicator()
                      : Text('Login'),
                ),
                if (viewModel.isLoggedIn)
                  SizedBox(height: 16.0),
                if (viewModel.isLoggedIn)
                  Text(
                    'Logged in successfully!',
                    style: TextStyle(color: Colors.green),
                  ),
                if (viewModel.isLoggedIn)
                  SizedBox(height: 16.0),
                if (viewModel.isLoggedIn)
                  Text('Token: ${viewModel.token}'),
              ],
            );
          },

        )

      ),
    );
  }

}